package exporter

import (
	"emc_vnx_exporter/utils"
	"github.com/prometheus/client_golang/prometheus"
	"io/ioutil"
	"log"
	"os/exec"
	"strings"
	"time"
)

type Port struct {
	Name          string
	SPPortID      string
	SPUID         string
	LinkStatus    string
	PortStatus    string
	SwitchPresent string
	SwitchUID     string
	SPSourceID    string
}

var (
	port = prometheus.NewGaugeVec(
		prometheus.GaugeOpts{
			Name: "vnx_get_all_port",
			Help: "Get All Port Info",
		},
		[]string{"Name", "SPPortID", "SPUID", "LinkStatus", "PortStatus", "SwitchPresent", "SwitchUID", "SPSourceID"},
	)
)

func PortGauge() *prometheus.GaugeVec {
	return port
}

func GetPortListMetrics(spIp string, user string, password string) {
	for {
		cmd := exec.Command("bash", "-c", "/opt/Navisphere/bin/naviseccli -h "+spIp+" -user "+user+" -password "+password+" -Scope 0 port -list | awk 'n==1{print} $0~/Information about each SPPORT:/{n=1}'")
		stdout, _ := cmd.StdoutPipe()
		defer stdout.Close()
		if err := cmd.Start(); err != nil {
			log.Fatalf("cmd.Start: %v", err)
		}
		result, _ := ioutil.ReadAll(stdout) // 读取输出结果
		resData := string(result)

		portList := strings.Split(resData, "\n\n")
		for _, portString := range portList {
			portItems := strings.Split(portString, "\n")
			data := new(Port)
			for _, portItem := range portItems {
				if portItem == "" {
					continue
				}
				value := portItem[strings.Index(portItem, ":")+1 : strings.Count(portItem, "")-1]
				value = strings.Replace(value, "  ", "", -1)
				if strings.Contains(portItem, "SP Name") {
					data.Name = value
				} else if strings.Contains(portItem, "SP Port ID") {
					data.SPPortID = value
				} else if strings.Contains(portItem, "SP UID") {
					data.SPUID = value
				} else if strings.Contains(portItem, "Link Status") {
					data.LinkStatus = value
				} else if strings.Contains(portItem, "Port Status") {
					data.PortStatus = value
				} else if strings.Contains(portItem, "Switch Present") {
					data.SwitchPresent = value
				} else if strings.Contains(portItem, "Switch UID") {
					data.SwitchUID = value
				} else if strings.Contains(portItem, "SP Source ID") {
					data.SPSourceID = value
				}
			}
			if data.Name != "" {
				port.WithLabelValues(
					data.Name,
					data.SPPortID,
					data.SPUID,
					data.LinkStatus,
					data.PortStatus,
					data.SwitchPresent,
					data.SwitchUID,
					data.SPSourceID,
				).Set(utils.PortStatusToFloat(data.PortStatus))
			}
		}
		time.Sleep(60 * time.Second)
	}
}
